package com.tanhua.server.controller;

import com.tanhua.autoconfig.templates.SmsTemplate;
import com.tanhua.model.db.User;
import com.tanhua.server.service.UserService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
public class LoginController {


    @Autowired
    private SmsTemplate smsTemplate;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private UserService userService;

    /**
     * 发送验证码
     * */
    @PostMapping("/login")
    public ResponseEntity login(@RequestBody Map map){
        //获取手机号
        String phone = map.get("phone").toString();
        //随机生成验证码
       // String code = RandomUtil.randomNumbers(6);
        String code = "123456";
        //调用方法发送短信
       // smsTemplate.sendSms(phone,code);
        System.out.println("发送成功：" + code);
        //存入redis
        redisTemplate.opsForValue().set("CODE:"+phone,code,5, TimeUnit.MINUTES);
        return ResponseEntity.ok(null);
    }
    /**
     * 根据手机号查询用户
     * */
    @GetMapping("/{mobile}")
    public ResponseEntity findByMobile(@PathVariable("mobile") String mobile) {

        User user = userService.findByMobile(mobile);

        return ResponseEntity.ok(user);
    }

    /**
     手机号注册登入
     * */
    @PostMapping("/loginVerification")
    public ResponseEntity loginVerification(@RequestBody Map map){
        //获取参数
        String phone = map.get("phone").toString();
        String code = map.get("verificationCode").toString();
        //登入
        Map retMap = userService.loginVerification(phone,code);


        return ResponseEntity.ok(retMap);
    }
}
